#include "nfcpeertopeer.h"

NfcPeerToPeer::NfcPeerToPeer(QObject *parent) :
    QObject(parent), nfcUri("urn:nfc:sn:com.nokia.nfcchat")
{
    nfcManager = new QNearFieldManager(this);
    connect(nfcManager, SIGNAL(targetDetected(QNearFieldTarget*)),
            this, SLOT(targetDetected(QNearFieldTarget*)));
    connect(nfcManager, SIGNAL(targetLost(QNearFieldTarget*)),
            this, SLOT(targetLost(QNearFieldTarget*)));

    // Only detect other NFC devices. Leave the phone to handle NFC tags.
    nfcManager->startTargetDetection(QNearFieldTarget::NfcForumDevice);

    nfcServer = new QLlcpServer(this);
    connect(nfcServer, SIGNAL(newConnection()),
            this, SLOT(handleNewConnection()));
    nfcServer->listen(nfcUri);

    nfcClientSocket = new QLlcpSocket(this);
    connect(nfcClientSocket, SIGNAL(readyRead()),
            this, SLOT(readText()));
}

void NfcPeerToPeer::targetDetected(QNearFieldTarget *target)
{
    emit chatMessage("Target detected");
    nfcClientSocket->connectToService(target, nfcUri);
}

void NfcPeerToPeer::targetLost(QNearFieldTarget *target)
{
    target->deleteLater();
    emit chatMessage("Target lost");
    nfcClientSocket->disconnectFromService();
}

void NfcPeerToPeer::handleNewConnection() {
    if (nfcServerSocket) { nfcServerSocket->deleteLater(); }
    nfcServerSocket = nfcServer->nextPendingConnection();
}

void NfcPeerToPeer::sendText(const QString& text) {
    if (nfcServerSocket && nfcServerSocket->isOpen()) {
        nfcServerSocket->write(text.toUtf8());
        emit chatMessage("Message sent");
    }
}

void NfcPeerToPeer::readText() {
    QByteArray rawData = nfcClientSocket->readAll();
    QString data = QString::fromUtf8(rawData.constData(), rawData.size());
    emit chatMessage(data);
}
